import { constantRoutes } from '@/router'
import { menuDataTranslate } from '@/utils'
import { getInfo } from '@/api/user'
import Layout from '@/layout'
import middleLayout from '@/layout/middleLayout'
import { childrenRoutes } from '@/router'

export const loadView = (view) => {
  if (process.env.NODE_ENV === 'development') {
    return (resolve) => require([`@/views${view}`], resolve)
  } else {
    return () => import(`@/views${view}`)
  }
}

const findItem = (arr, itemId) =>
  arr.reduce((a, item) => {
    if (a) return a
    if (item.meta.menuId === itemId) return item
    if (item.children) return findItem(item.children, itemId)
  }, null)

const getDefaultState = () => {
  return {
    routes: [],
    addRoutes: null,
    hasRoutes: false,
    limitMenuFunctionList: []
  }
}

/**
 * 把后台返回菜单组装成routes要求的格式
 */

export function getAsyncRoutes(routes) {
  const res = []
  const keys = ['path', 'name', 'children', 'meta', '_level']
  routes.forEach((item) => {
    const newItem = {}
    if (item.component) {
      if (item.component === 'layout/Layout') {
        newItem.component = Layout
        if (item._level === 2) {
          newItem.component = middleLayout
        }
      } else {
        try {
          newItem.component = loadView(item.component)
        } catch (err) {
          newItem.component = null
        }
      }
    }
    for (const key in item) {
      if (keys.includes(key)) {
        newItem[key] = item[key]
      }
    }
    if (newItem.children && newItem.children.length) {
      newItem.children = getAsyncRoutes(item.children)
    }
    if (newItem.path) {
      res.push(newItem)
    }
  })
  return res
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes) {
  routes.forEach((route) => {
    if (route._level === 2 && route.children) {
      route.children.forEach((route) => {
        route.hidden = true
      })
    }

    if (route.children && route.children.length > 1) {
      filterAsyncRoutes(route.children)
    }
  })
  return routes
}

function insertChildrenRoutes(asyncRoutes) {
  childrenRoutes.forEach((route) => {
    const _route = findItem(asyncRoutes, route.parentId)
    if (_route) {
      if (!_route.children) {
        _route.children = []
      }
      _route.children.push(route)
    }
  })
}

const state = getDefaultState()

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  RESET_ROUTES: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_HAS_ROUTES: (state, hasRoutes) => {
    state.hasRoutes = hasRoutes
  },
  SET_LIMIT_MENU_FUNCTION_LIST: (state, list) => {
    state.limitMenuFunctionList = list
  }
}

const actions = {
  generateRoutes({ commit }) {
    return new Promise(async (resolve) => {
      const data = await getInfo() // 获取到后台路由
      const tomsMenu = data.platformInfoList.find(
        (list) => list.platCode === 'TOMS'
      )

      const { limitMenuFuncCodeList, menuFunctionList } = data

      const filteredmenuFunctionList = menuFunctionList.filter(
        (o) => !limitMenuFuncCodeList.includes(o.menuFuncCode)
      )

      const mapFilteredmenuFunctionList = filteredmenuFunctionList.map(
        (o) => o.menuId
      )

      // TODO: 特殊处理，先写死，后面要优化
      // if (
      //   mapFilteredmenuFunctionList.filter((id) =>
      //     (id + '').startsWith('12401800')
      //   ).length > 0
      // ) {
      //   mapFilteredmenuFunctionList.push(12401800)
      // }

      commit('SET_LIMIT_MENU_FUNCTION_LIST', mapFilteredmenuFunctionList)

      const filteredMenu = tomsMenu.menuList.filter((menu) => {
        if (menu.showFlag === '0') {
          return false
        }
        return (
          !menu.href ||
          (menu.showFlag === '1' &&
            mapFilteredmenuFunctionList.includes(menu.menuId))
        )
      })

      console.log(filteredMenu)

      const menuList = menuDataTranslate(filteredMenu, 'menuId', 'parentMenuId')

      console.log(menuList)

      const asyncRoutes = getAsyncRoutes(menuList) // 对路由格式进行处理

      const filteredRoutes = filterAsyncRoutes(asyncRoutes)

      insertChildrenRoutes(filteredRoutes)
      commit('SET_ROUTES', filteredRoutes)
      resolve(filteredRoutes)
    })
  },
  resetRoutes({ commit }) {
    commit('RESET_ROUTES')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
